package com.sam.im.heiqun.uis.activities;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.support.v4.widget.SwipeRefreshLayout;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sam.im.heiqun.R;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.CircleNums;
import com.sam.im.heiqun.entities.CommontsEntity;
import com.sam.im.heiqun.entities.FeedPraisesEntity;
import com.sam.im.heiqun.entities.ImageEntity;
import com.sam.im.heiqun.entities.MyCircleItem;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.mvp.contract.CircleContract;
import com.sam.im.heiqun.mvp.modle.CircleItem;
import com.sam.im.heiqun.mvp.modle.CommentConfig;
import com.sam.im.heiqun.mvp.modle.CommentItem;
import com.sam.im.heiqun.mvp.modle.FavortItem;
import com.sam.im.heiqun.mvp.presenter.CirclePresenter;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.adapters.CircleAdapter;
import com.sam.im.heiqun.utils.CitySelectUtil;
import com.sam.im.heiqun.utils.HttpAssist;
import com.sam.im.heiqun.utils.ImageCropViewActivity;
import com.sam.im.heiqun.utils.MyDialog;
import com.sam.im.heiqun.utils.ToastUtil;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.sam.im.heiqun.utils.circleutils.CommonUtils;
import com.sam.im.heiqun.widgets.CommentListView;
import com.sam.im.heiqun.widgets.dialog.UpLoadDialog;
import com.sam.im.heiqun.widgets.imagepicker.PhotoPickerActivity;
import com.sam.im.heiqun.widgets.imagepicker.SelectModel;
import com.sam.im.heiqun.widgets.imagepicker.intent.PhotoPickerIntent;
import com.google.gson.Gson;
import com.malinskiy.superrecyclerview.OnMoreListener;
import com.malinskiy.superrecyclerview.SuperRecyclerView;
import com.soundcloud.android.crop.Crop;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.utils.TimeUtil;
import com.yuyh.library.view.image.CircleImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sam.im.heiqun.utils.StringUtils;
import pub.devrel.easypermissions.EasyPermissions;

import static com.soundcloud.android.crop.Crop.REQUEST_CROP;

/**
 * 朋友圈，首页列表
 */
public class CircleActivity extends YWActivity implements CircleContract.View, EasyPermissions.PermissionCallbacks {
    protected static final String TAG = CircleActivity.class.getSimpleName();
    private CircleAdapter circleAdapter;
    private LinearLayout edittextbody;
    private EditText editText;
    private ImageView sendIv;
    private int screenHeight;
    private int editTextBodyHeight;
    private int currentKeyboardH;
    private int selectCircleItemH;
    private int selectCommentItemOffset;
    private CirclePresenter presenter;
    private CommentConfig commentConfig;
    private SuperRecyclerView recyclerView;
    private RelativeLayout bodyLayout;
    private LinearLayoutManager layoutManager;
    // private TitleBar titleBar;
    private RelativeLayout titleBar ;
    private ImageView imBack;
    private TextView tvTitle ;
    private TextView tvRight ;
    private TextView tvTime ;

    private LinearLayout dynamicLayout  ;
    private CircleImageView friendIcon ;
    private TextView tvItem ;
    private final static int TYPE_PULLREFRESH = 1;
    private final static int TYPE_UPLOADREFRESH = 0;
    private UpLoadDialog uploadDialog;
    private SwipeRefreshLayout.OnRefreshListener refreshListener;
    private int pageNo = 0 ;
    private PopupMenu popupMenu; // 消息弹框菜单
    private Menu menu;
    public final  static  int CHOSE_IMG = 101 ;
    // private List<MyCircleItem.ListBean> data = new ArrayList<>();
    private LinearLayout nocircle ;
    private String choesimgpath;

    private String year = "" ;
    private String month = "" ;

    private boolean isCommitPL = false ;

    private List<MyCircleItem.ListBean> alldatas = new ArrayList<>();

    private Dialog dialog ;
    private static final int SDK_PERMISSION_REQUEST = 127;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_circle);
        EventBus.getDefault().register(this);
        presenter = new CirclePresenter(this);

        initView();
        //initPermission();

        //实现自动下拉刷新功能
        recyclerView.getSwipeToRefresh().post(new Runnable(){
            @Override
            public void run() {
                recyclerView.setRefreshing(true);//执行下拉刷新的动画
                refreshListener.onRefresh();//执行数据加载操作
            }
        });
    }


    /* private void initPermission() {
         String[] perms = {Manifest.permission.CALL_PHONE
                 , Manifest.permission.WRITE_EXTERNAL_STORAGE
                 , Manifest.permission.READ_EXTERNAL_STORAGE};
         if (EasyPermissions.hasPermissions(this, perms)) {
             // Already have permission, do the thing
             // ...
         } else {
             // Do not have permissions, request them now
             EasyPermissions.requestPermissions(this, "因为功能需要，需要使用相关权限，请允许",
                     100, perms);
         }
     }*/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getsendmsg(String even){
        if (even.equals("发布成功")||even.equals("点赞") || even.equals(Constant.BYB_FRIEND)){
            Log.i(TAG, "getsendmsg: -----------来了通知了-----------");
            presenter.loadData(1, ToolsUtils.getMyUserId(),1);
        }
    }
    @Override
    protected void onDestroy() {
        if(presenter !=null){
            presenter.recycle();
        }
        circleAdapter.getDatas().clear();
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @SuppressLint({ "ClickableViewAccessibility", "InlinedApi" })
    private void initView() {

        initTitle();
        initUploadDialog();
        nocircle = (LinearLayout) findViewById(R.id.nocircle);
        recyclerView = (SuperRecyclerView) findViewById(R.id.recyclerView);
        dynamicLayout = (LinearLayout) findViewById(R.id.dynamic_layout);
        friendIcon = (CircleImageView) findViewById(R.id.friend_icon);
        tvItem = (TextView) findViewById(R.id.tv_item);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        // recyclerView.addItemDecoration(new DividerItemDecorationUtils(this, LinearLayoutManager.HORIZONTAL,1, getResources().getColor(R.color.dialog_gray)));
        recyclerView.getMoreProgressView().getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;
        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (edittextbody.getVisibility() == View.VISIBLE) {
                    updateEditTextBodyVisible(View.GONE, null);
                    return true;
                }
                return false;
            }
        });
        //下拉刷新
        refreshListener = new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pageNo=1 ;
                presenter.loadData(pageNo, ToolsUtils.getMyUserId(),1);
            }
        };
        recyclerView.setRefreshListener(refreshListener);
        //上拉加载更多

        recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if(newState == RecyclerView.SCROLL_STATE_IDLE){

                    // Glide.with(CircleActivity.this).resumeRequests();
                }else{
                    // Glide.with(CircleActivity.this).pauseRequests();
                }
            }
        });

        circleAdapter = new CircleAdapter(this);
        circleAdapter.setCirclePresenter(presenter);
        recyclerView.setAdapter(circleAdapter);
        UserEntivity user = ToolsUtils.getUser();
        if (user != null) {
            Log.i("info","img=="+user.getFeedBackImage());
            if (user.getFeedBackImage() != null&&!StringUtils.isEmpty(user.getFeedBackImage())) {
                circleAdapter.setBackgroudUrl(user.getFeedBackImage());
            }
        }
        edittextbody = (LinearLayout) findViewById(R.id.editTextBodyLl);
        editText = (EditText) findViewById(R.id.circleEt);
        sendIv = (ImageView) findViewById(R.id.sendIv);
        sendIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isCommitPL){
                    isCommitPL = true ;
                    if (presenter != null) {
                        //发布评论
                        String content =  editText.getText().toString().trim();
                        if(TextUtils.isEmpty(content)){
                            Toast.makeText(CircleActivity.this, getResources().getString(R.string.pl_content_nonull), Toast.LENGTH_SHORT).show();
                            return;
                        }
                        //CommentConfig.Type.REPLY
                        presenter.addComment(content, commentConfig);
                    }
                    updateEditTextBodyVisible(View.GONE, null);
                }
            }
        });
        boolean circlenums = ToolsUtils.getCirclenums(this);
        circleAdapter.setOnnewsItemOclickListenler(new CircleAdapter.OnnewsItemOclickListenler() {
            @Override
            public void newsClick() {
                //EventBus.getDefault().post(new CircleNums("0"));
                ToolsUtils.saveCirclenums(CircleActivity.this,false);
                startActivity(new Intent(CircleActivity.this,CircleDetailActivity.class));
            }
        });
        circleAdapter.setOnbackgroudClickListenler(new CircleAdapter.OnbackgroudClickListenler() {
            @Override
            public void backgroudclick(View view) {
                initMenu(view);
            }
        });
        List<CircleNums> circleNumses = CircleNums.find(CircleNums.class, "unicid=? and isread=? and type!=?", new String[]{ToolsUtils.getMyUserId(), "0", Constant.MESSAGE_TYPR_CIRCLE+""});
        if (circleNumses != null && circleNumses.size() != 0) {
            CircleNums circleNums1 = circleNumses.get(circleNumses.size() - 1);
            circleAdapter.setUnread(circleNumses.size(),circleNums1);
        }else {
            circleAdapter.setUnread(0,null);
        }
        List<CircleNums> circleNumses1 = CircleNums.find(CircleNums.class, "unicid=? and isread=? and type=?", new String[]{ToolsUtils.getMyUserId(), "0", Constant.MESSAGE_TYPR_CIRCLE+""});
        if (circleNumses1.size()>0){
            for (int i = 0; i < circleNumses1.size(); i++) {
                circleNumses1.get(i).setIsread("1");
                circleNumses1.get(i).save();
            }
        }
        setViewTreeObserver();
//        getLocalDatas();
    }
    public void initMenu(View view) {
        popupMenu = new PopupMenu(this, view);
        menu = popupMenu.getMenu();
        // 通过XML文件添加菜单项
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.popup_menu_collects, menu);
        MenuItem item = menu.getItem(0);
        item.setTitle(getResources().getString(R.string.update_fm)); //这里对消息进行判断  是否可以撤回
        popupMenu.show();
        // 监听事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (item.getItemId()==R.id.delete){//更换相册封面
//                    PhotoPickerIntent pt = new PhotoPickerIntent(CircleActivity.this);
//                    pt.setSelectModel(SelectModel.MULTI);
//                    pt.setShowCarema(true); // 是否显示拍照， 默认false
//                    pt.setMaxTotal(1); // 最多选择照片数量，默认为9
//                    //pt.setImageConfig(conFig);
//                    startActivityForResult(pt,CHOSE_IMG);
                            getPersimmions();
                }
                return false;
            }
        });
    }
    boolean isgo = false ;
    @TargetApi(23)
    protected void getPersimmions() {
        isgo = false ;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            // 读写权限
            int pos = 0 ;
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
                pos ++ ;
            }
            if (addPermission(permissions, Manifest.permission.CAMERA)){
                pos ++ ;
            }
            if (2==pos){
                gotoPhoto();
            }
            if (permissions.size() > 0) {
                Log.i(TAG, "getPersimmions: --------001--------");
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }else {
            gotoPhoto();
        }
    }
    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case SDK_PERMISSION_REQUEST:
                Map<String, Integer> perms = new HashMap<String, Integer>();
//                perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
//                perms.put(Manifest.permission.RECORD_AUDIO, PackageManager.PERMISSION_GRANTED);
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);
                try {
                    int isgre = 0 ;
                    if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                        isgre ++;
                    }
                    if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                        isgre ++;
                    }
                    if (2 <= isgre){
                        gotoPhoto();
                    }else {
                        Toast.makeText(this, getResources().getString(R.string.disable_picture_permission_will_make_send_picture_unusable), Toast.LENGTH_SHORT)
                                .show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }

                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    private void gotoPhoto(){
        if (!isgo){
            PhotoPickerIntent pt = new PhotoPickerIntent(this);
            pt.setSelectModel(SelectModel.MULTI);
            pt.setShowCarema(true); // 是否显示拍照， 默认false
            pt.setMaxTotal(1); // 最多选择照片数量，默认为9
            //pt.setImageConfig(conFig);
            startActivityForResult(pt,CHOSE_IMG);
        }
        isgo = true ;
    }
    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)) {
                //拒绝了也是可以强行提示的，不过如果再也不提示的情况还没处理
                permissionsList.add(permission);
                return false;
            } else {
                permissionsList.add(permission);
                return false;
            }
        } else {

            return true;
        }
    }


    private void initUploadDialog() {
        uploadDialog = new UpLoadDialog(this);
    }

    private void initTitle() {
        titleBar = (RelativeLayout) findViewById(R.id.main_title_bar);
        imBack = (ImageView) findViewById(R.id.pre_v_back);
        tvTitle = (TextView) findViewById(R.id.pre_tv_title);
        tvRight = (TextView) findViewById(R.id.ok);
        tvTime = (TextView) findViewById(R.id.time);
        tvTitle.setText(getResources().getString(R.string.circle));
        tvRight.setText(getResources().getString(R.string.send_b));
        tvRight.setVisibility(View.VISIBLE);
        tvTime.setVisibility(View.VISIBLE);
//        tvRight.setBackgroundResource(R.drawable.shape_sure_bt);
        imBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        dialog = MyDialog.ShowDialog(CircleActivity.this, "", new String[]{getResources().getString(R.string.circle_txt), getResources().getString(R.string.circle_image),
                getResources().getString(R.string.circle_vedio)}, new MyDialog.DialogItemClickListener() {
            @Override
            public void confirm(String result) {
                if (getResources().getString(R.string.circle_txt).equals(result)){
                    SendCircleActivity.start(CircleActivity.this, 1);
                }else if (getResources().getString(R.string.circle_image).equals(result)){
                    startActivity(new Intent(CircleActivity.this,SendCircleActivity.class));
                }else if (getResources().getString(R.string.circle_vedio).equals(result)){
                    SendCircleActivity.start(CircleActivity.this, 2);
                }
            }
        });

        tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!dialog.isShowing()){
                    dialog.show();
                }

            }
        });
        tvTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CitySelectUtil.showWalletTimeDialog(CircleActivity.this, new CitySelectUtil.IOnCitySelectListener() {
                    @Override
                    public void onCitySelect(String province, String city) {
                        if (null == city) city = "0";
                        if (null == province) province = "0";
                        year = province ;
                        month = city ;
                        String time = province + "-" + (city.length() == 1 ? "0" + city : city);
                        Log.i("-----", "onCitySelect: ------time="+time);

                        List<MyCircleItem.ListBean> alldatas2 = new ArrayList<>();

                        alldatas2 = setShaiXuan(alldatas);
                        if (null!=alldatas2 && alldatas2.size() > 0)nocircle.setVisibility(View.GONE);
                        else nocircle.setVisibility(View.VISIBLE);
                        recyclerView.setRefreshing(false);
                        circleAdapter.setDatas(alldatas2);
                        circleAdapter.notifyDataSetChanged();

                    }
                }, TimeUtil.getYear3Time(), TimeUtil.getMonth3Time());
            }
        });
        /*titleBar = (TitleBar) findViewById(R.id.main_title_bar);
        titleBar.setTitle("朋友圈");
        titleBar.setTitleColor(getResources().getColor(R.color.white));
        titleBar.setBackgroundColor(getResources().getColor(R.color.title_bg));

        TextView textView = (TextView) titleBar.addAction(new TitleBar.TextAction("发布视频") {
            @Override
            public void performAction(View view) {
                //Toast.makeText(MainActivity.this, "敬请期待...", Toast.LENGTH_SHORT).show();

              //  QPManager.startRecordActivity(CircleActivity.this);
            }
        });*/
        // textView.setTextColor(getResources().getColor(R.color.white));
    }



    private void setViewTreeObserver() {
        bodyLayout = (RelativeLayout) findViewById(R.id.bodyLayout);
        final ViewTreeObserver swipeRefreshLayoutVTO = bodyLayout.getViewTreeObserver();
        swipeRefreshLayoutVTO.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                Rect r = new Rect();
                bodyLayout.getWindowVisibleDisplayFrame(r);
                int statusBarH =  getStatusBarHeight();//状态栏高度
                int screenH = bodyLayout.getRootView().getHeight();
                if(r.top != statusBarH ){
                    //在这个demo中r.top代表的是状态栏高度，在沉浸式状态栏时r.top＝0，通过getStatusBarHeight获取状态栏高度
                    r.top = statusBarH;
                }
                int keyboardH = screenH - (r.bottom - r.top);
                Log.d(TAG, "screenH＝ "+ screenH +" &keyboardH = " + keyboardH + " &r.bottom=" + r.bottom + " &top=" + r.top + " &statusBarH=" + statusBarH);

                if(keyboardH == currentKeyboardH){//有变化时才处理，否则会陷入死循环
                    return;
                }

                currentKeyboardH = keyboardH;
                screenHeight = screenH;//应用屏幕的高度
                editTextBodyHeight = edittextbody.getHeight();

                if(keyboardH<150){//说明是隐藏键盘的情况
                    updateEditTextBodyVisible(View.GONE, null);
                    return;
                }
                //偏移listview
                if(layoutManager!=null && commentConfig != null){
                    layoutManager.scrollToPositionWithOffset(commentConfig.circlePosition + CircleAdapter.HEADVIEW_SIZE, getListviewOffset(commentConfig));
                }
            }
        });
    }

    /**
     * 获取状态栏高度
     * @return
     */
    private int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if(edittextbody != null && edittextbody.getVisibility() == View.VISIBLE){
                //edittextbody.setVisibility(View.GONE);
                updateEditTextBodyVisible(View.GONE, null);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
    protected void dialog(final  String circleId) {
        AlertDialog.Builder builder = new AlertDialog.Builder(CircleActivity.this);
        builder.setMessage(getResources().getString(R.string.delete_ok));
        builder.setTitle(getResources().getString(R.string.tip));
        builder.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                PGService.getInstance().deletecircle(circleId,ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ValidateEntivity>() {
                    @Override
                    protected void onResultError(ApiException ex) {

                    }

                    @Override
                    public void onNext(ValidateEntivity validateEntivity) {
                        if (validateEntivity != null) {

                        }
                    }
                });

                List<MyCircleItem.ListBean> circleItems = circleAdapter.getDatas();
                for(int i=0; i<circleItems.size(); i++){
                    if(circleId.equals(circleItems.get(i).getFeedId())){
                        circleItems.remove(i);
                        circleAdapter.notifyDataSetChanged();
                        return;
                    }
                }
            }
        });
        builder.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }
    @Override
    public void update2DeleteCircle(String circleId) {
        dialog(circleId);
    }

    @Override
    public void update2AddFavorite(final int circlePosition, final FavortItem addItem) {
        List<MyCircleItem.ListBean> datas =  circleAdapter.getDatas();
        PGService.getInstance().getparise(ToolsUtils.getMyUserId(),datas.get(circlePosition).getFeedId()).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
            }

            @Override
            public void onNext(ValidateEntivity validateEntivity) {
                Toast.makeText(CircleActivity.this, getResources().getString(R.string.zan_success),Toast.LENGTH_SHORT).show();
//                presenter.loadData(1,ToolsUtils.getMyUserId(),1);
                //circleAdapter.notifyItemChanged(circlePosition);

                MyCircleItem.ListBean item = (MyCircleItem.ListBean) circleAdapter.getDatas().get(circlePosition);
                List<FeedPraisesEntity> commentItemList = item.getImFeedPraises();
                FeedPraisesEntity commontsEntity = new FeedPraisesEntity();
                commontsEntity.setFId(addItem.getId());
                commontsEntity.setCreateTime(""+System.currentTimeMillis());
                commontsEntity.setUserHeadUrl(ToolsUtils.getUser().getHeadUrl());
                commontsEntity.setUserId(ToolsUtils.getMyUserId());
                commontsEntity.setUserName(ToolsUtils.getUser().getNickName());

                commentItemList.add(commontsEntity);
                item.setImFeedPraises(commentItemList);
                circleAdapter.getDatas().set(circlePosition,item);
                Log.i(TAG, "onNext: -------------Comments.size()=" +
                        ((MyCircleItem.ListBean) circleAdapter.getDatas().get(circlePosition)).getImFeedComments().size());
//            circleAdapter.notifyDataSetChanged();
                circleAdapter.notifyItemChanged(circlePosition+1);

            }
        });
        if(addItem != null){
          /*  MyCircleItem.ListBean item = (MyCircleItem.ListBean) circleAdapter.getDatas().get(circlePosition);
            item.getFavorters().add(addItem);
            circleAdapter.notifyDataSetChanged();*/
            //circleAdapter.notifyItemChanged(circlePosition+1);
        }
    }

    @Override
    public void update2DeleteFavort(final int circlePosition) {
        List<MyCircleItem.ListBean> datas =  circleAdapter.getDatas();
        String feedId = datas.get(circlePosition).getFeedId();
        PGService.getInstance().delparise(feedId,ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                Toast.makeText(CircleActivity.this, getResources().getString(R.string.caozuo_fail),Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNext(ValidateEntivity validateEntivity) {
                if (validateEntivity != null) {
                    Toast.makeText(CircleActivity.this,validateEntivity.getInfo(),Toast.LENGTH_SHORT).show();
//                    presenter.loadData(1,ToolsUtils.getMyUserId(),1);

                    MyCircleItem.ListBean item = (MyCircleItem.ListBean) circleAdapter.getDatas().get(circlePosition);
                    List<FeedPraisesEntity> commentItemList = item.getImFeedPraises();
                    int pos = -1 ;
                    for (FeedPraisesEntity commontsEntity : commentItemList) {
                        pos++;
                        if (commontsEntity.getUserId().equals(ToolsUtils.getMyUserId())){
                            commentItemList.remove(pos);
                        }
                    }

                    item.setImFeedPraises(commentItemList);
                    circleAdapter.getDatas().set(circlePosition,item);
                    Log.i(TAG, "onNext: -------------Comments.size()=" +
                            ((MyCircleItem.ListBean) circleAdapter.getDatas().get(circlePosition)).getImFeedComments().size());
//            circleAdapter.notifyDataSetChanged();
                    circleAdapter.notifyItemChanged(circlePosition+1);

                }
            }
        });

        /*CircleItem item = (CircleItem) circleAdapter.getDatas().get(circlePosition);
        List<FavortItem> items = item.getFavorters();
        for(int i=0; i<items.size(); i++){
            if(favortId.equals(items.get(i).getId())){
                items.remove(i);
                circleAdapter.notifyDataSetChanged();
                //circleAdapter.notifyItemChanged(circlePosition+1);
                return;
            }
        }*/
    }

    @Override
    public void update2AddComment(final int circlePosition, final CommentItem addItem, final CommentConfig config) {
        List<MyCircleItem.ListBean> datas =  circleAdapter.getDatas();
        String s = editText.getText().toString();
        if (StringUtils.isEmpty(s)){
            Toast.makeText(CircleActivity.this,getResources().getString(R.string.pl_content_nonull),Toast.LENGTH_SHORT).show();
        }else {
            String replyid = "";
            if (config.commentType==CommentConfig.Type.REPLY){//如果是回复类型才传replyid
                replyid = config.getReplyUserid();
            }

            final String mreplyid = "".equals(replyid)?"0":replyid ;

            PGService.getInstance().getconmment(ToolsUtils.getMyUserId(),replyid,datas.get(circlePosition).getFeedId(), s).subscribe(new AbsAPICallback<ValidateEntivity>() {
                @Override
                protected void onResultError(ApiException ex) {

                }

                @Override
                public void onNext(ValidateEntivity validateEntivity) {
                    Toast.makeText(CircleActivity.this, getResources().getString(R.string.pl_success),Toast.LENGTH_SHORT).show();
//                    presenter.loadData(1,ToolsUtils.getMyUserId(),1);
                    if(addItem != null){
                        MyCircleItem.ListBean item = (MyCircleItem.ListBean) circleAdapter.getDatas().get(circlePosition);
                        List<CommontsEntity> commentItemList = item.getImFeedComments();
                        CommontsEntity commontsEntity = new CommontsEntity();
                        commontsEntity.setCId(addItem.getId());
                        commontsEntity.setCommentText(addItem.getContent());
                        commontsEntity.setCreateTime(""+System.currentTimeMillis());

                        String head = "";
                        String name = "";
                        if (null!=config && null!=config.replyUser){
                            head = config.replyUser.getHeadUrl();
                            name = config.replyUser.getName();
                        }

                        commontsEntity.setReplyUserHeadUrl(null==addItem.getToReplyUser()?head:addItem.getToReplyUser().getHeadUrl());
                        commontsEntity.setReplyUserId(null==addItem.getToReplyUser()?mreplyid:addItem.getToReplyUser().getId());
                        commontsEntity.setReplyUserName(null==addItem.getToReplyUser()?name:addItem.getToReplyUser().getName());
//                        commontsEntity.setUserHeadUrl(addItem.getUser().getHeadUrl());
//                        commontsEntity.setUserId(addItem.getUser().getId());
//                        commontsEntity.setUserName(addItem.getUser().getName());
                        commontsEntity.setUserHeadUrl(ToolsUtils.getUser().getHeadUrl());
                        commontsEntity.setUserId(ToolsUtils.getMyUserId());
                        commontsEntity.setUserName(ToolsUtils.getUser().getNickName());

                        commentItemList.add(commontsEntity);
                        item.setImFeedComments(commentItemList);
                        circleAdapter.getDatas().set(circlePosition,item);
                        Log.i(TAG, "onNext: -------------Comments.size()="+((MyCircleItem.ListBean) circleAdapter.getDatas().get(circlePosition)).getImFeedComments().size());
//            circleAdapter.notifyDataSetChanged();
                        circleAdapter.notifyItemChanged(circlePosition+1);
                    }
                    isCommitPL = false ;
                }
            });

        }

        //清空评论文本
        editText.setText("");
    }

    @Override
    public void update2DeleteComment(int circlePosition, String commentId) {
        CircleItem item = (CircleItem) circleAdapter.getDatas().get(circlePosition);
        List<CommentItem> items = item.getComments();
        for(int i=0; i<items.size(); i++){
            if(commentId.equals(items.get(i).getId())){
                items.remove(i);
//                circleAdapter.notifyDataSetChanged();
                circleAdapter.notifyItemChanged(circlePosition);
                return;
            }
        }
    }

    @Override
    public void updateEditTextBodyVisible(int visibility, CommentConfig commentConfig) {
        this.commentConfig = commentConfig;
        edittextbody.setVisibility(visibility);

        measureCircleItemHighAndCommentItemOffset(commentConfig);

        if(View.VISIBLE==visibility){
            editText.requestFocus();
            //弹出键盘
            CommonUtils.showSoftInput( editText.getContext(),  editText);

        }else if(View.GONE==visibility){
            //隐藏键盘
            CommonUtils.hideSoftInput( editText.getContext(),  editText);
        }
    }

    @Override
    public void showGiftSelecter(int visibility,final CommentConfig commentConfig) {
        this.commentConfig = commentConfig;
        MyDialog.ShowGiftDialog(CircleActivity.this, new MyDialog.DialogItemClickListener() {
            @Override
            public void confirm(String result) {
                if (null!=result && result.length() > 0){
                    MyCircleItem.ListBean item = (MyCircleItem.ListBean) circleAdapter.getDatas().get(commentConfig.circlePosition);
                    if (null!= item){
                        //发送礼物
                        sendFeedGift(item.getFeedId(), item.getUserId(), result);
                    }
                }
            }
        });

    }

    private void sendFeedGift(String feedId, String destId, String gift){
        PGService.getInstance().sendFeedGift(feedId, destId, gift, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                Toast.makeText(CircleActivity.this,getResources().getString(R.string.caozuo_fail),Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNext(ValidateEntivity validateEntivity) {
                if (validateEntivity != null) {
                    ToastUtil.showtoast(CircleActivity.this,getResources().getString(R.string.song_gift_success));
                }
            }
        });
    }

    private void getLocalDatas(){
        List<MyCircleItem.ListBean> localData = MyCircleItem.ListBean.listAll(MyCircleItem.ListBean.class);
        if (null!=localData && localData.size() > 0){
            try {
                alldatas.clear();
                alldatas.addAll(localData);
//            localData = setShaiXuan(localData);
//            recyclerView.setRefreshing(false);
                circleAdapter.setDatas(localData);
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }

    @Override
    public void update2loadData(int loadType, List<MyCircleItem.ListBean> datas,int type) {
        switch (type){
            case 1:
                Log.i("info","刷新、、、");

                alldatas.clear();
                alldatas.addAll(datas);
                datas = setShaiXuan(datas);
                final List<MyCircleItem.ListBean> datasm = datas;
                recyclerView.setRefreshing(false);
                circleAdapter.setDatas(datas);

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (null!=datasm && datasm.size() > 0){
                            MyCircleItem.ListBean.deleteAll(MyCircleItem.ListBean.class);//如果请求到数据，清空数据库
                            for (int i = 0; i < datasm.size(); i++) {

                                if (null!=datasm.get(i) && null!=datasm.get(i).getImFeedPraises() && datasm.get(i).getImFeedPraises().size() > 0){
                                    for (int j = 0; j < datasm.get(i).getImFeedPraises().size(); j++) {
                                        datasm.get(i).getImFeedPraises().get(j).save();
                                    }
                                }
                                if (null!=datasm.get(i) && null!=datasm.get(i).getImFeedComments() && datasm.get(i).getImFeedComments().size() > 0){
                                    for (int j = 0; j < datasm.get(i).getImFeedComments().size(); j++) {
                                        datasm.get(i).getImFeedComments().get(j).save();
                                    }
                                }
                                datasm.get(i).save();
                            }
                        }
                    }
                }).start();


                break;
            case 0:
                Log.i("info","下拉更多");
                alldatas.addAll(datas);
                datas = setShaiXuan(datas);
                circleAdapter.getDatas().addAll(datas);
                break;
        }
        //  Log.i("info","适配器中的数据=="+circleAdapter.getDatas().size()%20);
        if((circleAdapter.getDatas().size())%20==0){
            recyclerView.setupMoreListener(new OnMoreListener() {
                @Override
                public void onMoreAsked(int overallItemsCount, int itemsBeforeMore, int maxLastVisiblePosition) {
                    //loadmore
                    Log.i("info","进入上拉加载更多");
                    presenter.loadData(pageNo,ToolsUtils.getMyUserId(),0);
                }
            },1);
        }else{
            recyclerView.removeMoreListener();
            recyclerView.hideMoreProgress();
        }
        if (datas.size()==0){
            recyclerView.removeMoreListener();
            recyclerView.hideMoreProgress();
        }
        //Log.i("info","datasize=="+data.size());

        // recyclerView.removeMoreListener();
        switch (type){
            case 1:
                Log.i("info","刷新、、、");
                circleAdapter.notifyDataSetChanged();
                break;
            case 0:
                Log.i("info","下拉更多");
                alldatas.addAll(datas);
                datas = setShaiXuan(datas);
                circleAdapter.getDatas().addAll(datas);

//                circleAdapter.notifyDataSetChanged();

                if (null!=datas && datas.size() > 0){
                    if (circleAdapter.getDatas().size() > datas.size()){
                        int start = circleAdapter.getDatas().size() - datas.size() ;
                        circleAdapter.notifyItemRangeInserted(start,datas.size());
                    }
                }
                break;
        }

        EventBus.getDefault().post("朋友动态已读");
        ShowNoCircle();
    }

    private List<MyCircleItem.ListBean> setShaiXuan(List<MyCircleItem.ListBean> datas){
        if (null==datas || datas.size() <=0){
            return new ArrayList<>();
        }
        Log.i("-----", "setShaiXuan: ============year="+year+"==month=="+month);
        if ("".equals(year) || "".equals(month)){
            return datas ;
        }else {
            List<MyCircleItem.ListBean> datas2 = new ArrayList<>();
            for (int i = 0; i < datas.size(); i++) {

                Date d1=new Date(Long.parseLong(datas.get(i).getCreateTime()));
                Calendar calendar=Calendar.getInstance();
                calendar.setTime(d1);
                int y = calendar.get(Calendar.YEAR);
                int m = d1.getMonth() + 1 ;
                Log.i("-----", "setShaiXuan: ============y="+y+"==m=="+m);
                if (y == Integer.parseInt(year) && m == Integer.parseInt(month)){
                    datas2.add(datas.get(i));
                }
            }
            return datas2 ;
        }
    }

    private String getTime(long time){
        SimpleDateFormat format=new SimpleDateFormat("MM-dd");
        Date d1=new Date(time);
        return format.format(d1);
    }

    private void ShowNoCircle(){
        if (circleAdapter.getDatas().size()<=0){
            nocircle.setVisibility(View.VISIBLE);
        }else {
            nocircle.setVisibility(View.GONE);
        }
    }


    /**
     * 测量偏移量
     * @param commentConfig
     * @return
     */
    private int getListviewOffset(CommentConfig commentConfig) {
        if(commentConfig == null)
            return 0;
        //这里如果你的listview上面还有其它占高度的控件，则需要减去该控件高度，listview的headview除外。
        //int listviewOffset = mScreenHeight - mSelectCircleItemH - mCurrentKeyboardH - mEditTextBodyHeight;
        int listviewOffset = screenHeight - selectCircleItemH - currentKeyboardH - editTextBodyHeight - titleBar.getHeight();
        if(commentConfig.commentType == CommentConfig.Type.REPLY){
            //回复评论的情况
            listviewOffset = listviewOffset + selectCommentItemOffset;
        }
        Log.i(TAG, "listviewOffset : " + listviewOffset);
        return listviewOffset;
    }

    private void measureCircleItemHighAndCommentItemOffset(CommentConfig commentConfig){
        if(commentConfig == null)
            return;

        int firstPosition = layoutManager.findFirstVisibleItemPosition();
        //只能返回当前可见区域（列表可滚动）的子项
        View selectCircleItem = layoutManager.getChildAt(commentConfig.circlePosition + CircleAdapter.HEADVIEW_SIZE - firstPosition);

        if(selectCircleItem != null){
            selectCircleItemH = selectCircleItem.getHeight();
        }

        if(commentConfig.commentType == CommentConfig.Type.REPLY){
            //回复评论的情况
            CommentListView commentLv = (CommentListView) selectCircleItem.findViewById(R.id.commentList);
            if(commentLv!=null){
                //找到要回复的评论view,计算出该view距离所属动态底部的距离
                View selectCommentItem = commentLv.getChildAt(commentConfig.commentPosition);
                if(selectCommentItem != null){
                    //选择的commentItem距选择的CircleItem底部的距离
                    selectCommentItemOffset = 0;
                    View parentView = selectCommentItem;
                    do {
                        int subItemBottom = parentView.getBottom();
                        parentView = (View) parentView.getParent();
                        if(parentView != null){
                            selectCommentItemOffset += (parentView.getHeight() - subItemBottom);
                        }
                    } while (parentView != null && parentView != selectCircleItem);
                }
            }
        }
    }

    String videoFile;
    String [] thum;
    private Uri newUri;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i("info",requestCode+"===="+resultCode);
        switch (requestCode){
            case CHOSE_IMG:
                if (resultCode==RESULT_OK){
                    ArrayList<String> stringArrayListExtra = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    if (stringArrayListExtra.size()>0){
                        choesimgpath = stringArrayListExtra.get(0);
                        Log.i("info","返回的路径s=="+ choesimgpath);
                        final File file = new File(choesimgpath);
                        if (file.exists()){
//                                Uri uri = Uri.fromFile(file);
//                                ToolsUtils.cropImageUri(this,uri,600,470,3333);
                            //ImageCropViewActivity.start(CircleActivity.this,choesimgpath,600,470,3333);
                            Uri uri = Uri.fromFile(file);
//                            ToolsUtils.cropImageUri(this,uri,800,400,3333);
                            //      ImageCropViewActivity.start(this,chosepath,800,400,3333);

                            newUri  =  Uri.fromFile(new File( getCacheDir(), "cropped"+System.currentTimeMillis()));

                            Crop.of(uri, newUri).asSquare().start(this);

                        }else {
                            ToolsUtils.showToast(CircleActivity.this,getResources().getString(R.string.file_no));
                        }
                    }
                }
                break;
            case REQUEST_CROP:
            case 3333:
                if (choesimgpath != null) {
                    Log.i("info","data1=="+choesimgpath);
                    circleAdapter.setBackgroudUrl(choesimgpath);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            String s1 = HttpAssist.uploadFile(new File(choesimgpath), "", false);
                            Log.i("info","s1=="+s1);
                            try {
                                ImageEntity imageEntity = new Gson().fromJson(s1,ImageEntity.class);
                                EventBus.getDefault().post(imageEntity.getData().getInfo().get(0));
                            }catch (Exception e){
                            }
                        }
                    }).start();

                }
                break;
        }

    }

    @Override
    public void showLoading(String msg) {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showError(String errorMsg) {

    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        //Toast.makeText(this, "onPermissionsGranted  requestCode: " + requestCode , Toast.LENGTH_LONG).show();
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        //Toast.makeText(this, "您拒绝了相关权限，可能会导致相关功能不可用" , Toast.LENGTH_LONG).show();
        /*if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this, getString(R.string.rationale_ask_again))
                    .setTitle(getString(R.string.title_settings_dialog))
                    .setPositiveButton(getString(R.string.setting))
                    .setNegativeButton(getString(R.string.cancel), null *//* click listener *//*)
                    .setRequestCode(RC_SETTINGS_SCREEN)
                    .build()
                    .show();
        }*/
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setcirclenums(final String s){
        if (s.equals("动态已读")){
            circleAdapter.setUnread(0,null);
        }else if (s.contains("http")){//图片上传完毕
            PGService.getInstance().setcircleback(s,ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ValidateEntivity>() {
                @Override
                protected void onResultError(ApiException ex) {
                    //ToolsUtils.showToast(CircleActivity.this,"修改失败");
                }
                @Override
                public void onNext(ValidateEntivity validateEntivity) {
                    if (validateEntivity != null) {
                        //ToolsUtils.showToast(CircleActivity.this,validateEntivity.getInfo());
                       /* List<ImFriendEntivity> imFriendEntivities = ImFriendEntivity.find(ImFriendEntivity.class, "id=?", new String[]{ToolsUtils.getMyUserId()});
                        if (imFriendEntivities != null) {
                            if (imFriendEntivities.size()>0){
                                Log.i("info","userentity="+imFriendEntivities.get(0).toString());
                                imFriendEntivities.get(0).setFeedBackImage(s);
                                imFriendEntivities.get(0).save();
                            }
                        }*/
                        UserEntivity user = ToolsUtils.getUser();
                        if (user != null) {
                            user.setFeedBackImage(s);
                            user.save();
                        }
                        //circleAdapter.setBackgroudUrl(choesimgpath);
                    }
                }
            });

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //这里显示最后一次
    public void getcircleNums(CircleNums s){
        Log.i(TAG, "getcircleNums: -------接收统治方法--------");
//        if (s!=null) {
        List<CircleNums> circleNumses = CircleNums.find(CircleNums.class, "unicid=? and isread=? and type!=?", new String[]{ToolsUtils.getMyUserId(), "0", Constant.MESSAGE_TYPR_CIRCLE+""});
        if (circleNumses != null && circleNumses.size() != 0) {
            CircleNums circleNums1 = circleNumses.get(circleNumses.size() - 1);
            circleAdapter.setUnread(circleNumses.size(),circleNums1);
        }else {

        }
//        }
    }
}
